from datetime import timedelta
from django.db import transaction
from ability.models import Order
from rest_framework import serializers
import ability.timeutil as timeutil

class OrdersSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
    user_name = serializers.SerializerMethodField()
    status_label = serializers.SerializerMethodField()
    order_type_label = serializers.SerializerMethodField()

    class Meta:
        model = Order
        fields = ['user_name', 'order_no', 'create_time', 'total_fee', 'status', 'status_label', 'order_type_label', 'order_type', 'body']

    def get_user_name(self, obj):
        return obj.user.real_name

    def get_order_type_label(self, obj):
        if obj.order_type == Order.ORDER_TYPE_EXPERIMENT:
            return '实验'
        if obj.order_type == Order.ORDER_TYPE_COURSE:
            return '课程'
        if obj.order_type == Order.ORDER_TYPE_EXAM:
            return '考试'

    def get_status_label(self, obj):
        if obj.status == Order.STATUS_PAYED:
            return '支付完成'
        if obj.status == Order.STATUS_PAYING:
            # todo does this order timeout
            with transaction.atomic():
                if timeutil.expired(timedelta(minutes=15) + obj.create_time):
                    obj.status = Order.STATUS_TIMEOUT
                    obj.save()
                    return '支付超时'
            return '待支付'
        if obj.status == Order.STATUS_TIMEOUT:
            return '支付超时'
